package com.example.dryyzx.controller;

import com.example.dryyzx.dao.AccountMapper;
import com.example.dryyzx.dao.UserMapper;
import com.example.dryyzx.encapsulation.UsermanagerPageEncapsulation;
import com.example.dryyzx.encapsulation.UsermanagerPageEncapsulation2;
import com.example.dryyzx.entity.Account;
import com.example.dryyzx.entity.User;
import com.example.dryyzx.entity.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Controller
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AccountMapper accountMapper;

    private static String byte2Hex(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        String temp;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuilder.append("0");
            }
            stringBuilder.append(temp);
        }
        return stringBuilder.toString();
    }

    public static String getSha256Str(String str) {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }


    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    public List<Account> search_account_by_user(List<User> user ){
        int i;
        List<Account> account = new ArrayList<Account>();
        Account accounttmp = null;
        for (i = 0; i < user.size(); i++) {
            accounttmp = accountMapper.selectByUserId(user.get(i).getId());
            account.add(i, accounttmp);
        }
        return account;
    }

    List<UsermanagerPageEncapsulation> getEncapsulation(List<User> user,List<Account> account,int limit){
        List<UsermanagerPageEncapsulation> encapsulation = new ArrayList<UsermanagerPageEncapsulation>();
        for (int i=0;i<limit;i++) {
            UsermanagerPageEncapsulation tmp = new UsermanagerPageEncapsulation();
            tmp.id = user.get(i).getId();
            tmp.account_number = account.get(i).getAccountNumber();
            tmp.pwd = account.get(i).getPassword();
            tmp.uname = user.get(i).getName();
            tmp.sex = user.get(i).getSex();
            tmp.age = user.get(i).getAge();
            tmp.telephone = user.get(i).getPhone();
            tmp.power = user.get(i).getJob();
            tmp.salary = user.get(i).getSalary();
            tmp.employ_number = user.get(i).getEmployeeNumber();
            tmp.remarks = user.get(i).getRemarks();
            tmp.entry_time = sdf.format(user.get(i).getEntryTime());
            if(user.get(i).getIsLeaving()==false)
                tmp.status ="在岗";
            else
                tmp.status ="离职";
            encapsulation.add(i, tmp);
        }
        return encapsulation;
    }

    @RequestMapping(value = "usermanager_page/getUser", method = RequestMethod.POST)
    public @ResponseBody
    String search_user(int page, HttpSession session) {
        int data_per_page = 6;
        int total_data_no = userMapper.countUser();
        if(total_data_no<=0)
            return new JsonResult(false, "未查找到用户").toString();

        int offset=(page-1)*data_per_page;
        int limit;
        if(total_data_no-offset<data_per_page)
            limit=total_data_no-offset;
        else
            limit=data_per_page;
        if(total_data_no<=offset)
            return new JsonResult(false, "页数过大，数据不够").toString();

        List<User> user=userMapper.selectByLimitAndOffset(limit,offset);

        List<Account> account =search_account_by_user(user);
        if (user.size() != account.size())
            return new JsonResult(false, "未查找到部分用户的账户").toString();

        UsermanagerPageEncapsulation2 total_data=new UsermanagerPageEncapsulation2();
        List<UsermanagerPageEncapsulation> encapsulation=getEncapsulation(user,account,limit);
        total_data.user_list=encapsulation;
        total_data.total_page=(total_data_no-1)/data_per_page+1;

        return new JsonResult(true, total_data).toString();
    }

    @RequestMapping(value = "usermanager_page/getUserById", method = RequestMethod.POST)
    public @ResponseBody
    String search_user_by_id(int id, HttpSession session) {
        List<User> user=new ArrayList<User>();
        User usertmp=userMapper.selectByPrimaryKey(id);
        if(usertmp==null)
            return new JsonResult(false, "未查找到该用户").toString();
        else
            user.add(0,usertmp);

        List<Account> account =search_account_by_user(user);
        if (user.size() != account.size())
            return new JsonResult(false, "未查找到该用户的账户").toString();

        List<UsermanagerPageEncapsulation> total_data=getEncapsulation(user,account,1);

        return new JsonResult(true, total_data).toString();
    }

    @RequestMapping(value = "usermanager_page/getUserByName", method = RequestMethod.POST)
    public @ResponseBody
    String search_user_by_name(String name, int page, HttpSession session) {
        int data_per_page = 6;
        int total_data_no = userMapper.countUserByName(name);
        if(total_data_no<=0)
            return new JsonResult(false, "未查找到用户").toString();

        int offset=(page-1)*data_per_page;
        int limit;
        if(total_data_no-offset<data_per_page)
            limit=total_data_no-offset;
        else
            limit=data_per_page;
        if(total_data_no<=offset)
            return new JsonResult(false, "页数过大，数据不够").toString();

        List<User> user=userMapper.selectByLimitAndOffsetName(limit,offset,name);

        List<Account> account =search_account_by_user(user);
        if (user.size() != account.size())
            return new JsonResult(false, "未查找到部分用户的账户").toString();

        UsermanagerPageEncapsulation2 total_data=new UsermanagerPageEncapsulation2();
        List<UsermanagerPageEncapsulation> encapsulation=getEncapsulation(user,account,limit);
        total_data.user_list=encapsulation;
        total_data.total_page=(total_data_no-1)/data_per_page+1;

        return new JsonResult(true, total_data).toString();
    }

    @RequestMapping(value = "usermanager_page/editUser",method = RequestMethod.POST)
    public @ResponseBody void editUser(String name,String sex,String salary,String age,String telephone,
                                       String power,String remarks,String status,String pwd,String id){
        User user = userMapper.selectByPrimaryKey(Integer.valueOf(id));
        user.setName(name);
        user.setSex(sex);
        user.setSalary(Integer.valueOf(salary));
        user.setAge(Integer.valueOf(age));
        user.setPhone(telephone);
        //user.setEmployeeNumber(employ_number);
        user.setJob(power);
        user.setRemarks(remarks);
        if(Objects.equals(status, "离职")) {
            user.setIsLeaving(true);
        } else if (Objects.equals(status, "在岗")) {
            user.setIsLeaving(false);
        } else {System.out.println("user的status/is_leaving输入错误"); }
        user.setId(Integer.valueOf(id));
        userMapper.updateByPrimaryKeySelective(user);

        Account editedAccount;
        editedAccount = accountMapper.selectByUserId(Integer.parseInt(id));
        editedAccount.setPassword(pwd);
        accountMapper.updateByPrimaryKeySelective(editedAccount);
    }

    @RequestMapping(value = "usermanager_page/addUser",method = RequestMethod.POST)
    public @ResponseBody String addUser(String name,String sex,String salary,String age,String telephone,String employ_number,
                                      String power,String remarks,String status,String entry_time) throws ParseException {
        User user = new User();
        user.setName(name);
        user.setSex(sex);
        user.setSalary(Integer.valueOf(salary));
        user.setAge(Integer.valueOf(age));
        user.setPhone(telephone);
        user.setEmployeeNumber(employ_number);
        user.setJob(power);
        user.setRemarks(remarks);
        if(entry_time != null && !entry_time.equals("")) {
            user.setEntryTime(sdf.parse(entry_time));
        }else {
            return new JsonResult(false,"请填写入职时间").toString();
        }
        if(Objects.equals(status, "离职")) {
            user.setIsLeaving(true);
        } else if (Objects.equals(status, "在岗")) {
            user.setIsLeaving(false);
        } else {return new JsonResult(false,"员工状态填写错误").toString(); }
        //user.setId(Integer.valueOf(id));
        userMapper.insertSelective(user);

        //不要在这个后面打断点 会只生成user不生成account的
        Account account = new Account();
        int newUserId = userMapper.lastUserId();
        if(power.equals("管理员")){
            account.setAccountNumber("admin"+newUserId);
            account.setType("管理员");
        } else {
            account.setAccountNumber("worker"+newUserId);
            account.setType("用户");
        }
        account.setUserId(newUserId);
        account.setEnable(true);
        String psw = (Objects.equals(user.getJob(), "管理员") ?"admin":"worker") + employ_number;
        account.setPassword(getSha256Str(psw));
        accountMapper.insertSelective(account);
        return new JsonResult(true,null).toString();
    }

    @RequestMapping(value = "/usermanager_page/delete_person", method = RequestMethod.POST)
    public @ResponseBody String deleteUser(String id,HttpSession session) throws ParseException {
        User deleteUser = new User();
        deleteUser.setId(Integer.valueOf(id));
        deleteUser.setIsLeaving(true);
        Date leaving_time=new Date();
        deleteUser.setLeavingTime(leaving_time);
        int delete1 = userMapper.updateByPrimaryKeySelective(deleteUser);
        if (delete1 == 0)
            return new JsonResult(false, "找不到要删除的用户！无法进行删除").toString();

        Account deleteAccount = new Account();
        Account accounttmp = accountMapper.selectByUserId(Integer.valueOf(id));
        if(accounttmp==null){
            deleteUser.setIsLeaving(false);
            deleteUser.setLeavingTime(null);
            userMapper.updateByPrimaryKeySelective(deleteUser);    //回滚数据
            userMapper.setLeavingTimeNullByPrimaryKey(Integer.valueOf(id));
            return new JsonResult(false, "找不到要删除用户的账户！无法进行删除").toString();
        }
        deleteAccount.setAccountNumber(accounttmp.getAccountNumber());
        deleteAccount.setEnable(false);
        int delete2 = accountMapper.updateByPrimaryKeySelective(deleteAccount);
        if(delete2==0){
            deleteUser.setIsLeaving(false);
            deleteUser.setLeavingTime(null);
            userMapper.updateByPrimaryKeySelective(deleteUser);    //回滚数据
            userMapper.setLeavingTimeNullByPrimaryKey(Integer.valueOf(id));
            return new JsonResult(false, "无法删除用户的账户！").toString();
        }

        session.setAttribute("deleteUser", deleteUser);
        return new JsonResult(true, delete1).toString();
    }
}
